﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Threading;
using ComicIsland.App.Controls;
using ComicIsland.Common;
using ComicIsland.Common.Entities.ComicDatabase;
using ComicIsland.Common.Entities.InterfaceJson;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views.ReadComic
{
    public partial class ReadPagePanorama : PhoneApplicationPage, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private const double _dPadding = 5;

        private DispatcherTimer timeFairy = new DispatcherTimer();

        private int nTaskTotal = 6;

        private int nEntryTag;

        private int nCatalogue;

        private int nReadPageNo;

        private Storyboard sbOperator;

        private List<int> ImageIDs = new List<int>();

        private ObservableCollection<JsonComicContentInfo> _TmpImages = new ObservableCollection<JsonComicContentInfo>();



        private double nWidth = (double)Application.Current.Host.Content.ActualWidth + 5;

        private double nHeigth = (double)Application.Current.Host.Content.ActualHeight + 5;

        private bool pIsTap;

        private bool pIsDoubleTap;

        private DispatcherTimer pTapFairy = new DispatcherTimer();

        private System.Windows.Input.GestureEventArgs gesture;

        private StackPanel hGrid = new StackPanel();

        private StackPanel sTsCtlArea = new StackPanel();

        private StackPanel sLeftCtlArea = new StackPanel();

        private StackPanel sRightCtlArea = new StackPanel();

        private StackPanel sUpCtlArea = new StackPanel();

        private StackPanel sDownDtlArea = new StackPanel();

        private bool _isHelpPage;

        private bool isPinch;

        private bool isDrag;

        private bool isGestureOnTarget;

        private Point _ePoint;

        private Point _cPoint;

        private int comicId = 0, comicPartId = 0;
        private string comicTitle = string.Empty, comicPartTitle = string.Empty;
        private int _imagesIndex = -1;
        private ObservableCollection<DbImage> ImagesTable = new ObservableCollection<DbImage>();
        private List<ImagePlane> _imageViews;
        private ImageFrame _imgPanel;

        public List<ImagePlane> CtlImageViews
        {
            get
            {
                if (this._imageViews == null)
                {
                    try
                    {
                        this._imageViews = Variables.GetChildObjects<ImagePlane>(this.CanvasImageView, "");
                    }
                    catch
                    {
                    }
                }
                return this._imageViews;
            }
        }

        public ReadPagePanorama()
        {
            InitializeComponent();
            //
            this._imgPanel = new ImageFrame();
            this.CanvasImageView.DataContext = this._imgPanel;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string tmpComicId, tmpComicPartId;
            base.NavigationContext.QueryString.TryGetValue("comicId", out tmpComicId);
            int.TryParse(tmpComicId, out comicId);
            if (comicId <= 0)
            {
                base.NavigationService.GoBack();
                return;
            }
            base.NavigationContext.QueryString.TryGetValue("comicPartId", out tmpComicPartId);
            int.TryParse(tmpComicPartId, out comicPartId);
            if (comicPartId <= 0)
            {
                base.NavigationService.GoBack();
                return;
            }
            //
            LoadComicChapterImage();

        }



        void LoadComicChapterImage()
        {
            //加载缓存中的图片
            this.LoadCacheImage();
            //获取网络图片
        }

        /// <summary>
        /// 加载缓存中的图片
        /// </summary>
        void LoadCacheImage()
        {
            this.ImagesTable = App.comicDbHelper.ImageGetByComicIdAndChapterId(this.comicId, this.comicPartId);
            if (!(this.ImagesTable != null && this.ImagesTable.Count > 0))
            {
                return;            
            }
            if (base.SupportedOrientations == (SupportedPageOrientation)2)
            {
                Canvas.SetLeft(this.CanvasImageView, -this.nWidth);
            }
            else
            {
                Canvas.SetLeft(this.CanvasImageView, -this.nHeigth);
            }
            InitCtlModel();
            ImagePlane.SetQImage(this.ImageLFrame, this.ImagesTable[0]);
            ImagePlane.SetQImage(this.ImageMidFrame, this.ImagesTable[1]);
            ImagePlane.SetQImage(this.ImageRFrame, this.ImagesTable[2]);
        }

        private void InitCtlModel()
        {
            if (base.SupportedOrientations == (SupportedPageOrientation)2)
            {
                this.CanvasImageView.SetValue(Canvas.LeftProperty, -this.nHeigth);
                double num = 0;
                foreach (ImagePlane ctlImageView in this.CtlImageViews)
                {
                    ctlImageView.Orientation = ComicIsland.Common.Helper.SrnOrientation.Landscape;
                    ctlImageView.SetValue(Canvas.LeftProperty, num);
                    num = num + this.nHeigth;
                }
                this.SetScreenSize((double)800, (double)480);
                return;
            }
            this.CanvasImageView.SetValue(Canvas.LeftProperty, -this.nWidth);
            double num1 = 0;
            foreach (ImagePlane imagePlane in this.CtlImageViews)
            {
                imagePlane.Orientation = ComicIsland.Common.Helper.SrnOrientation.Portrait;
                imagePlane.SetValue(Canvas.LeftProperty, num1);
                num1 = num1 + this.nWidth;
            }
            this.SetScreenSize((double)480, (double)800);
        }

        private void SetScreenSize(double width, double height)
        {
            foreach (ImagePlane ctlImageView in this.CtlImageViews)
            {
                ctlImageView.ScreenWidth = width;
                ctlImageView.ScreenHeight = height;
                ctlImageView.InitCtlProperty();
            }
        }

        private bool CheckIndexValid(int index)
        {
            if (index < 0)
            {
                return false;
            }
            return index < this.ImagesTable.Count();
        }

        private void LoadChapterImage()
        {
            DbImage item;
            DbImage comicImage;
            if (base.SupportedOrientations == (SupportedPageOrientation)2)
            {
                Canvas.SetLeft(this.CanvasImageView, -this.nWidth);
            }
            else
            {
                Canvas.SetLeft(this.CanvasImageView, -this.nHeigth);
            }
            try
            {
                this._imgPanel.MidFrame = this.ImagesTable[this._imagesIndex];
                if (!this.CheckIndexValid(this._imagesIndex - 1))
                {
                    //this._TmpImages = this.GetChapterImgs(false);
                    //ImageFrame imageFrame = this._imgPanel;
                    //if (this._TmpImages.Count > 0)
                    //{
                    //    item = this._TmpImages[this._TmpImages.Count - 1];
                    //}
                    //else
                    //{
                    //    item = null;
                    //}
                    //imageFrame.LeftFrame = item;
                }
                else
                {
                    this._imgPanel.LeftFrame = this.ImagesTable[this._imagesIndex - 1];
                }
                if (!this.CheckIndexValid(this._imagesIndex + 1))
                {
                    //this._TmpImages = this.GetChapterImgs(true);
                    //ImageFrame imageFrame1 = this._imgPanel;
                    //if (this._TmpImages.Count > 0)
                    //{
                    //    comicImage = this._TmpImages[0];
                    //}
                    //else
                    //{
                    //    comicImage = null;
                    //}
                    //imageFrame1.RightFrame = comicImage;
                }
                else
                {
                    this._imgPanel.RightFrame = this.ImagesTable[this._imagesIndex + 1];
                }
            }
            catch
            {
            }
        }



        private void LayoutOnDoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }

        private void GridLightTap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }

        private void SetScrnStyle(object sender, EventArgs e)
        {

        }

        private void ComicContents(object sender, EventArgs e)
        {

        }

        private void SetLight_Click(object sender, EventArgs e)
        {

        }

        private void PinShellToDesk(object sender, EventArgs e)
        {

        }

        private void FastHelp_Click(object sender, EventArgs e)
        {

        }
        
        private void AddManipulation()
		{
            this.LayoutRoot.ManipulationStarted += OnManipulationStarted;
            this.LayoutRoot.ManipulationDelta += OnManipulationDelta;
            this.LayoutRoot.ManipulationCompleted += OnManipulationCompleted;
            this.LayoutRoot.Tap += LayoutOnTap;
		}


        private void LayoutOnTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (this.ImageMidFrame.Mutexes || !this.ImageMidFrame.IsDragHorizontal)
            {
                return;
            }
            this.pIsDoubleTap = false;
            if (!this.pIsTap)
            {
                this.pIsTap = true;
                this.gesture = e;
                this.pTapFairy.Start();
            }
        }

       private void OnManipulationStarted(object sender, System.Windows.Input.ManipulationStartedEventArgs e)
        {
        }

       private void OnManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
        {
            if (this.isDrag)
            {
                this.isDrag = false;
                //this.OnDragCompleted();
                if (e.IsInertial)
                {
                    this.OnFlick(sender, e);
                }
            }
            if (this.isPinch)
            {
                this.isPinch = false;
                //this.OnPinchCompleted();
            }
        }

       private void OnManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            bool flag = this.isPinch;
            bool flag1 = this.isDrag;
            this.isPinch = e.PinchManipulation != null;
            this.isDrag = (e.PinchManipulation != null ? false : !flag);
            if (flag1)
            {
                bool flag2 = this.isDrag;
            }
            if (flag && !this.isPinch)
            {
               // this.OnPinchCompleted();
            }
            if (flag1 && this.isDrag)
            {
                this.OnDragDelta(sender, e);
            }
            if (flag && this.isPinch)
            {
                //this.OnPinchDelta(sender, e);
            }
            if (!flag1 && this.isDrag)
            {
                Rect rect = new Rect(0, 0, this.LayoutRoot.ActualWidth, this.LayoutRoot.ActualHeight);
                this.isGestureOnTarget = rect.Contains(e.ManipulationOrigin);
                this.OnDragStarted(e);
            }
            if (!flag && this.isPinch)
            {
                Rect rect1 = new Rect(0, 0, this.LayoutRoot.ActualWidth, this.LayoutRoot.ActualHeight);
                this.isGestureOnTarget = rect1.Contains(e.PinchManipulation.Original.PrimaryContact);
                //this.OnPinchStarted(sender, e);
            }
        }

       private void OnFlick(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
       {
           bool flag = this.isGestureOnTarget;
       }

       private void OnDragStarted(System.Windows.Input.ManipulationDeltaEventArgs e)
       {
           if (this.isGestureOnTarget)
           {
               if (this.sbOperator != null)
               {
                   this.sbOperator.Pause();
               }
               Point point = new Point(0, 0);
               Point point1 = point;
               this._cPoint = point;
               this._ePoint = point1;
               this.ImageMidFrame.DragStarted();
           }
       }

       private void OnDragDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
       {
           if (this.isGestureOnTarget)
           {
               if (this.ImageMidFrame.Mutexes)
               {
                   return;
               }
               this.ImageMidFrame.DragDelta(e);
               this._ePoint = e.DeltaManipulation.Translation;
               this._cPoint = e.CumulativeManipulation.Translation;
               if (this.ImageMidFrame.IsDragHorizontal)
               {
                   //if (this.IsComicFront() || this.IsComicRear())
                   //{
                   //    return;
                   //}
                   double left = Canvas.GetLeft(this.CanvasImageView);
                   Canvas.SetLeft(this.CanvasImageView, left + this._ePoint.X);
               }
           }
       }

       

    }
}